import * as THREE from "three"
import { OrbitControls } from "three/examples/jsm/Addons.js";

/**
 * 移动3D对象到原点，并且设置相机到合适位置
 * @param {THREE.Object3D} object
 * @param {THREE.Camera} camera
 * @param {OrbitControls} controls
 */
const fitObject3DToCamera = (object, camera, controls) => {

    object.updateMatrixWorld();

    const box = new THREE.Box3().setFromObject(object);
    const size = box.getSize(new THREE.Vector3()).length();
    const center = box.getCenter(new THREE.Vector3());

    controls.reset();

    object.position.x -= center.x;
    object.position.y -= center.y;
    object.position.z -= center.z;

    controls.maxDistance = size * 5;

    camera.near = size / 50;
    camera.far = size * 50;
    camera.updateProjectionMatrix();

    camera.position.copy(center);
    camera.position.set(size, size / 2, size)
    camera.lookAt(center);

    controls.saveState();

}

/**
 * 设置相机到相对3D对象的合适位置
 * @param {THREE.Object3D} object
 * @param {THREE.Camera} camera
 * @param {OrbitControls} controls
 */
const fitCameraToObject3D = (object, camera, controls) => {
    object.updateMatrixWorld();

    const box = new THREE.Box3().setFromObject(object)
    const size = box.getSize(new THREE.Vector3()).length();
    const center = box.getCenter(new THREE.Vector3());

    controls.reset();

    camera.near = size / 50;
    camera.far = size * 50;
    camera.updateProjectionMatrix();
    camera.position.copy(center);
    camera.position.add(new THREE.Vector3(size, size / 2, size))

    controls.maxDistance = size * 5;
    controls.target.copy(center)
    controls.saveState();

}

export {
    fitObject3DToCamera,
    fitCameraToObject3D,
}